import { getApiToken } from "@/api/module/U2U";
import { exchange } from "@/api/module/transaction";
import { CenterPopupComponent } from "@/components/CenterPopupComponent/CenterPopupComponent";
import HeaderComponent from "@/components/HeaderComponent/HeaderComponent";
import { useAppSelector } from "@/hooks/useAppSelector";
import getAssetsFile from "@/utils/pub-use";

import { Input, Image, Toast } from "antd-mobile";
import { useState } from "react";
import { useTranslation } from "react-i18next";
import { useNavigate } from "react-router-dom";

const AssetsComponent = () => {
  const { t } = useTranslation();
  const userInfo = useAppSelector((state) => state.userInfo.userInfo);
  return (
    <div className="mt-4">
      <div className="flex items-center justify-between asstest mx-2 bg-bg-1 py-4 px-4 rounded-xl"></div>
      <div className="value text-white-1 py-12 px-5 bg-custom-gradient-1 rounded-xl relative -top-4 flex items-center justify-center">
        <div className="stb w-1/2">
          <div className="opacity-50">{t("USDTBanlance")}</div>
          <div className="font-bold text-2xl">${userInfo.USDT.balance}</div>
        </div>
        <div className="zcb w-1/2">
          <div className="opacity-50">{t("XJBBanlance")}</div>
          <div className="font-bold text-2xl">${userInfo.XJB.balance}</div>
        </div>
      </div>
    </div>
  );
};
const FormComponent = () => {
  const navigate = useNavigate();

  const { t } = useTranslation();
  const typeList = [
    {
      pay: "XJB",
      get: "ZCB",
    },
    {
      pay: "USDT",
      get: "ZCB",
    },
  ];
  const [active, setActive] = useState(0);
  const [value, setValue] = useState("");
  const [password, setPassword] = useState("");
  const confirm = async () => {
    try {
      Toast.show({
        icon: "loading",
      });
      const res = await exchange({
        APITOKEN: APIToken,
        amount: value,
        currency_from: typeList[active].pay,
        password: password,
        currency_to: typeList[active].get,
      });
      Toast.clear();
      Toast.show({
        content: res.msg,
      });
      res.code == 0 &&
        (() => {
          setValue("");
          setPassword("");
        })();
      if (res.code == 1) {
        navigate("/updatePassword");
      }
      setAPIToken("");
    } catch (error) {
      Toast.clear();
      console.log(error);
      setVisible(false);
      setAPIToken("");
    }
  };

  const [visible, setVisible] = useState(false);
  const [APIToken, setAPIToken] = useState("");
  const reqApiToken = async () => {
    try {
      if (!value || !password) {
        Toast.show({
          content: t("enterCompleteInformation"),
        });
        return;
      }
      // if (!password) {
      //   Toast.show({
      //     content: '请输入2FA OTP',
      //   });
      //   return;
      // }
      if (!APIToken) {
        const res = await getApiToken();
        setAPIToken(res.data.api_token);
      }

      setVisible(true);
    } catch (error) {
      console.log(error);
    }
  };
  return (
    <div
      className="mt-4"
      style={{
        fontSize: "95%",
      }}
    >
      <div className="type">
        <div>{t("transferType")}</div>
        <div>
          {typeList.map((item, index) => {
            return (
              <div
                onClick={() => setActive(index)}
                key={index}
                className="flex items-center bg-bg-1 py-4 mt-3 px-3 rounded-lg "
              >
                {active != index ? (
                  <Image width={16} src={getAssetsFile("home/inactive.png")} />
                ) : (
                  <Image width={16} src={getAssetsFile("home/active.png")} />
                )}
                <span className="ml-2 w-20">{t(item.pay)}</span>
                <span className="mx-4 text-font-9 font-bold">
                  {t("exchange")}
                </span>{" "}
                <span>{t(item.get)}</span>
              </div>
            );
          })}
        </div>
      </div>
      <div className="number mt-4">
        <div>{t("exchangeNumber")}</div>
        <div className="bg-bg-1 py-4 mt-3 px-3 rounded-lg flex items-center">
          <span className="font-bold text-lg">$</span>
          <Input
            style={{
              "--font-size": "14px",
              "--color": "#fff",
            }}
            className="ml-2"
            placeholder={`${t("enter")}`}
            value={value}
            onChange={(val) => {
              setValue(val);
            }}
          />
        </div>
      </div>
      <div className="password mt-4">
        <div>{t("password")}</div>
        <Input
          style={{
            "--font-size": "14px",
            "--color": "#fff",
          }}
          type="password"
          className="bg-bg-1 py-4 mt-3 px-3 rounded-lg "
          placeholder={`${t("enter")}`}
          value={password}
          onChange={(val) => {
            setPassword(val);
          }}
        />
      </div>
      <div
        onClick={reqApiToken}
        className="mt-6 bg-bg-16 py-4 rounded-md text-center text-base"
      >
        {t("confirm")}
      </div>
      <CenterPopupComponent
        visible={visible}
        setVisible={setVisible}
        title="exchange"
        content={`${typeList[active].pay}${t("exchange")}${value}${typeList[active].get}`}
        onClick={() => confirm()}
      />
    </div>
  );
};
export default function Exchange() {
  return (
    <div className="text-white-1 px-4 pb-24">
      <HeaderComponent
        title="exchange"
        centerStyle={{
          fontSize: "18px",
        }}
      />
      <AssetsComponent />
      <FormComponent />
    </div>
  );
}
